<template>
  <div class="main">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        label-width="80px"
        class="search-form"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input
            v-model="searchForm.nickName"
            placeholder="请输入昵称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input
            v-model="searchForm.phonenumber"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="searchForm.sex"
            placeholder="请选择性别"
            clearable
            style="width: 120px"
          >
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
            <el-option label="未知" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline :icon="Search" class="mr-1" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline :icon="Refresh" class="mr-1" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <div class="table-title">
          <h3>用户列表</h3>
        </div>
        <div class="table-actions">
          <el-button type="primary" @click="handleAdd">
            <IconifyIconOffline :icon="Plus" class="mr-1" />
            新增用户
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedUsers.length"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline :icon="Delete" class="mr-1" />
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 用户表格 -->
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="用户ID" width="80" />
        <el-table-column label="头像" width="80" align="center">
          <template #default="{ row }">
            <el-avatar
              :size="40"
              :src="formatAvatarUrl(row.avatar)"
              :alt="row.userName"
              fit="cover"
            >
              <template #default>
                <el-icon><User /></el-icon>
              </template>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="nickName" label="昵称" width="120">
          <template #default="{ row }">
            {{ row.nickName || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phonenumber" label="手机号" width="130" />
        <el-table-column prop="sexName" label="性别" width="80" />
        <el-table-column prop="statusName" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roleNames" label="角色" width="150">
          <template #default="{ row }">
            <div class="role-tags">
              <el-tag
                v-for="role in row.roles"
                :key="role.id"
                type="primary"
                size="small"
                class="role-tag"
              >
                {{ role.roleName }}
              </el-tag>
              <span v-if="!row.roles || row.roles.length === 0" class="no-role">
                未分配角色
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="loginDate" label="最后登录" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.loginDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button
              type="info"
              size="small"
              link
              @click="handleViewProfile(row)"
            >
              详情
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              :disabled="isAdminUser(row)"
              :title="isAdminUser(row) ? '管理员账户不允许编辑' : ''"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status === 1 ? 'warning' : 'success'"
              size="small"
              link
              :disabled="isAdminUser(row)"
              :title="isAdminUser(row) ? '管理员账户不允许禁用' : ''"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? "禁用" : "启用" }}
            </el-button>
            <el-button
              type="info"
              size="small"
              link
              :disabled="isAdminUser(row)"
              :title="isAdminUser(row) ? '管理员账户不允许重置密码' : ''"
              @click="handleResetPassword(row)"
            >
              重置密码
            </el-button>

            <el-button
              type="danger"
              size="small"
              link
              :disabled="isAdminUser(row)"
              :title="isAdminUser(row) ? '管理员账户不允许删除' : ''"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <UserForm
      v-model:visible="formVisible"
      :form-data="formData"
      :is-edit="isEdit"
      @success="handleFormSuccess"
    />

    <!-- 重置密码对话框 -->
    <ResetPasswordDialog
      v-model:visible="resetPasswordVisible"
      :user-data="currentUser"
      @success="handleResetPasswordSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { User } from "@element-plus/icons-vue";
import { IconifyIconOffline } from "@/components/ReIcon";

import AvatarUploader from "@/components/AvatarUploader/index.vue";
import UserForm from "./components/UserForm.vue";
import ResetPasswordDialog from "./components/ResetPasswordDialog.vue";

import {
  getUserPageApi,
  deleteUserApi,
  batchDeleteUsersApi,
  updateUserStatusApi,
  getUserId,
  type UserInfo,
  type UserPageQuery
} from "@/api/user-management";

// 图标
import Search from "~icons/ep/search";
import Refresh from "~icons/ep/refresh";
import Plus from "~icons/ep/plus";
import Delete from "~icons/ep/delete";

defineOptions({
  name: "SystemUser"
});

// 路由实例
const router = useRouter();

// 响应式数据
const loading = ref(false);
const tableData = ref<UserInfo[]>([]);
const selectedUsers = ref<UserInfo[]>([]);
const formVisible = ref(false);
const resetPasswordVisible = ref(false);

const isEdit = ref(false);
const formData = ref<UserInfo | null>(null);
const currentUser = ref<UserInfo | null>(null);

// 搜索表单
const searchForm = reactive<UserPageQuery>({
  userName: "",
  nickName: "",
  email: "",
  phonenumber: "",
  status: undefined,
  sex: ""
});

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 获取用户列表
const getUserList = async () => {
  loading.value = true;
  try {
    const params: UserPageQuery = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    };
    const response = await getUserPageApi(params);
    if (response.code === 200) {
      tableData.value = response.data?.records || [];
      pagination.total = response.data?.total || 0;
    } else {
      ElMessage.error(response.message || "获取用户列表失败");
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  getUserList();
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    userName: "",
    email: "",
    phonenumber: "",
    status: undefined,
    sex: ""
  });
  pagination.current = 1;
  getUserList();
};

// 新增用户
const handleAdd = () => {
  formData.value = null;
  isEdit.value = false;
  formVisible.value = true;
};

// 查看用户详情
const handleViewProfile = (row: UserInfo) => {
  const userId = getUserId(row);
  if (!userId || userId === 0) {
    ElMessage.error("无法获取用户ID");
    return;
  }

  // 跳转到用户详情页面
  router.push(`/system/user/profile/${userId}`);
};

// 编辑用户
const handleEdit = (row: UserInfo) => {
  if (isAdminUser(row)) {
    ElMessage.warning("管理员账户不允许编辑");
    return;
  }

  const userId = getUserId(row);
  console.log("编辑用户数据:", row);
  console.log("获取到的用户ID:", userId);

  if (!userId || userId === 0) {
    ElMessage.error("无法获取用户ID，请刷新页面后重试");
    return;
  }

  // 确保formData包含正确的userId
  // 创建一个新对象，避免引用原始对象
  const userData = { ...row };

  // 确保所有可能的ID字段都设置正确
  userData.userId = userId;
  userData.id = userId;
  userData.userId = userId;
  userData.id = userId;
  userData.userId = userId;

  console.log("设置了所有可能的ID字段:", userData);
  formData.value = userData;

  console.log("设置的formData:", formData.value);
  isEdit.value = true;
  formVisible.value = true;
};

// 删除用户
const handleDelete = async (row: UserInfo) => {
  if (isAdminUser(row)) {
    ElMessage.warning("管理员账户不允许删除");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.userName}" 吗？`,
      "删除确认",
      {
        type: "warning"
      }
    );

    const response = await deleteUserApi(getUserId(row));
    if (response.code === 200) {
      ElMessage.success("删除成功");
      getUserList();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    console.error("删除用户失败:", error);
  }
};

// 批量删除
const handleBatchDelete = async () => {
  const adminUsers = selectedUsers.value.filter(user => isAdminUser(user));
  if (adminUsers.length > 0) {
    ElMessage.warning("选择的用户中包含管理员账户，无法删除");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      "批量删除确认",
      {
        type: "warning"
      }
    );

    const userIds = selectedUsers.value.map(user => user.userId);
    const response = await batchDeleteUsersApi(userIds);
    if (response.code === 200) {
      ElMessage.success("批量删除成功");
      selectedUsers.value = [];
      getUserList();
    } else {
      ElMessage.error(response.message || "批量删除失败");
    }
  } catch (error) {
    console.error("批量删除失败:", error);
  }
};

// 切换用户状态
const handleToggleStatus = async (row: UserInfo) => {
  const userId = getUserId(row);
  console.log("切换用户状态:", row);
  console.log("用户ID:", userId);
  console.log("当前状态:", row.status);

  if (isAdminUser(row)) {
    ElMessage.warning("不能修改管理员账户的状态");
    return;
  }

  const newStatus = row.status === 1 ? 0 : 1;
  const action = newStatus === 1 ? "启用" : "禁用";

  console.log("新状态:", newStatus);

  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 "${row.userName}" 吗？`,
      `${action}确认`,
      {
        type: "warning"
      }
    );

    console.log("调用API:", `updateUserStatusApi(${userId}, ${newStatus})`);
    const response = await updateUserStatusApi(userId, newStatus);
    console.log("API响应:", response);

    if (response.code === 200) {
      ElMessage.success(`${action}成功`);
      getUserList();
    } else {
      ElMessage.error(response.message || `${action}失败`);
    }
  } catch (error) {
    console.error(`${action}用户失败:`, error);
    ElMessage.error(`${action}失败: ${error.message || error}`);
  }
};

// 重置密码
const handleResetPassword = (row: UserInfo) => {
  if (isAdminUser(row)) {
    ElMessage.warning("管理员账户不允许重置密码");
    return;
  }

  const userId = getUserId(row);
  console.log("重置密码用户数据:", row);
  console.log("获取到的用户ID:", userId);

  if (!userId || userId === 0) {
    ElMessage.error("无法获取用户ID，请刷新页面后重试");
    return;
  }

  // 确保currentUser包含正确的userId
  // 创建一个新对象，避免引用原始对象
  const userData = { ...row };

  // 确保所有可能的ID字段都设置正确
  userData.userId = userId;
  userData.id = userId;
  userData.userId = userId;
  userData.id = userId;
  userData.userId = userId;

  console.log("设置了所有可能的ID字段:", userData);
  currentUser.value = userData;

  console.log("设置的currentUser:", currentUser.value);
  resetPasswordVisible.value = true;
};

// 表格选择变化
const handleSelectionChange = (selection: UserInfo[]) => {
  selectedUsers.value = selection;
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  getUserList();
};

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current;
  getUserList();
};

// 表单提交成功
const handleFormSuccess = () => {
  formVisible.value = false;
  getUserList();
};

// 重置密码成功
const handleResetPasswordSuccess = () => {
  resetPasswordVisible.value = false;
  ElMessage.success("密码重置成功");
};

// 判断是否为管理员用户
const isAdminUser = (user: UserInfo): boolean => {
  if (!user) return false;

  // 1. 检查用户名是否为admin
  if (user.userName === "admin") {
    return true;
  }

  // 2. 检查角色是否包含admin
  if (
    user.roles &&
    user.roles.some(
      role => role.roleKey === "admin" || role.roleName === "管理员"
    )
  ) {
    return true;
  }

  // 3. 检查角色名称字符串（兼容不同的数据格式）
  if (user.roleNames && user.roleNames.includes("管理员")) {
    return true;
  }

  return false;
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 格式化头像URL
const formatAvatarUrl = (url: string): string => {
  if (!url) return "";

  // 如果已经是完整URL，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // 如果是相对路径，添加基础URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};

// 初始化
onMounted(() => {
  getUserList();
});
</script>

<style lang="scss" scoped>
.main {
  /* 完全移除padding，不需要内边距 */
  padding: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 8px;

    .el-form-item__label {
      width: 80px !important;
      padding-right: 12px;
      font-weight: 600;
      color: #303133;
      text-align: right;
    }
  }
}

.table-card {
  .table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;

    .table-title h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }

    .table-actions {
      display: flex;
      gap: 10px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;

  .role-tag {
    margin: 0;
  }

  .no-role {
    font-size: 12px;
    font-style: italic;
    color: var(--el-text-color-secondary);
  }
}

.mr-1 {
  margin-right: 4px;
}
</style>
